package com.baidu.mail.service.impl;


import com.baidu.mail.service.sendMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class sendMailServiceImpl implements sendMailService {

    @Autowired
    private JavaMailSender javaMailSender;
    // 时间处理
    Date date = new Date();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /*
    * 收件人
    * 发件人
    * 主题（邮件标题）
    * 正文（邮件正文）
    * */
    private String to = "15778605738@163.com"; // 收件人
    private String from = "hypo.chiu@qq.com"; // 发件人
    private String subject = "测试发送邮件标题"; // 邮件标题
    private String text = "测试发送邮件正文" + simpleDateFormat.format(date)+"<a href='https://www.baidu.com'>点击跳转</a>"; // 邮件正文

    @Override
    public void sendSimpleMail() {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setTo(to);
        simpleMailMessage.setFrom(from+"(张三)");
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(text);
        // 把上面定义的邮件内容传入simpleMailMessage对象里

        // 发送邮件
        javaMailSender.send(simpleMailMessage);

    }

    @Override
    public void sendMimeMail() {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
            mimeMessageHelper.setTo(to);
            mimeMessageHelper.setFrom(from+"(张三)");
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(text,true);
            // 把上面定义的邮件内容传入simpleMailMessage对象里
            javaMailSender.send(mimeMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
